package com.sunday.pinxinghui.model.mine;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.sunday.common.model.ResultDO;
import com.sunday.common.utils.Constants;
import com.sunday.common.utils.ToastUtils;
import com.sunday.common.widgets.EmptyLayout;
import com.sunday.common.widgets.ptr.PtrClassicFrameLayout;
import com.sunday.common.widgets.ptr.PtrDefaultHandler;
import com.sunday.common.widgets.ptr.PtrFrameLayout;
import com.sunday.common.widgets.ptr.PtrHandler;
import com.sunday.common.widgets.recyclerView.HorizontalDividerItemDecoration;
import com.sunday.pinxinghui.R;
import com.sunday.pinxinghui.adapter.CommonAdapter;
import com.sunday.pinxinghui.adapter.OrderAdapter;
import com.sunday.pinxinghui.adapter.ViewHolder;
import com.sunday.pinxinghui.base.BaseApplication;
import com.sunday.pinxinghui.base.BaseLazyFragment;
import com.sunday.pinxinghui.entity.Order;
import com.sunday.pinxinghui.entity.Voucher;
import com.sunday.pinxinghui.model.WebViewActivity;
import com.sunday.pinxinghui.model.lifecircle.MakeCouponCommentActivity;
import com.sunday.pinxinghui.model.order.ApplyRefundActivity;
import com.sunday.pinxinghui.model.order.MakeCommentActivity;
import com.sunday.pinxinghui.model.order.OrderDetailActivity;
import com.sunday.pinxinghui.model.order.OrderListFragment;
import com.sunday.pinxinghui.model.order.OrderPayActivity;
import com.sunday.pinxinghui.model.order.RefundDetailActivity;
import com.sunday.pinxinghui.network.ApiClient;

import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;


/**
 * Created by 刘涛 on 2017/8/27.
 */

public class CouponListFragment extends BaseLazyFragment {

    @Bind(R.id.recycler_view)
    RecyclerView recyclerView;
    @Bind(R.id.ptr_frame)
    PtrClassicFrameLayout ptrFrame;
    @Bind(R.id.empty_layout)
    EmptyLayout emptyLayout;

    private int type;//1:优惠券 2：电子券
    private long memberId;
    private int pageNo = 1, lastVisibleItem;

    private List<Voucher> dataSet = new ArrayList<>();
    private CommonAdapter<Voucher> adapter;
    private boolean isCanloadMore;
    private LinearLayoutManager layoutManager;

    public static CouponListFragment newInstance(int type) {
        CouponListFragment fragment = new CouponListFragment();
        Bundle bundle = new Bundle();
        bundle.putInt("type", type);
        fragment.setArguments(bundle);
        return fragment;
    }

    private final static String TAG = "CouponListFragment";

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            type = getArguments().getInt("type");
        }
        Log.v(TAG, "onCreate" + type);
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        isPrepared = true;
        lazyLoad();
        Log.v(TAG, "onViewCreated" + type);
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        rootView = inflater.inflate(R.layout.fragment_order_list_fragment, container, false);
        ButterKnife.bind(this, rootView);
        Log.v(TAG, "onCreateView" + type);
        return rootView;

    }


    @Override
    protected void lazyLoad() {
        super.lazyLoad();
        if (!isPrepared || !isVisible) {
            return;
        }
        initRefreshLayout();
        isPrepared = false;
        memberId = BaseApplication.getInstance().getMember().getId();
        ptrFrame.autoRefresh();
        Log.v(TAG, "lazyLoad" + type);
    }

    private void initRefreshLayout() {
        if (type == 1) {
            adapter = new CommonAdapter<Voucher>(mContext, R.layout.list_voucher_item, dataSet) {
                @Override
                public void convert(ViewHolder holder, Voucher voucher, int position) {
                    bind(holder, voucher, position);
                }
            };
        } else {
            adapter = new CommonAdapter<Voucher>(mContext, R.layout.list_shop_voucher_item, dataSet) {
                @Override
                public void convert(ViewHolder holder, Voucher voucher, int position) {
                    bind1(holder, voucher, position);
                }
            };
        }
        layoutManager = new LinearLayoutManager(mContext);
        recyclerView.setLayoutManager(layoutManager);
        recyclerView.setPadding(12, 12, 12, 12);
        recyclerView.setAdapter(adapter);
        recyclerView.addItemDecoration(new HorizontalDividerItemDecoration.Builder(mContext)
                .drawable(R.drawable.horizontal_space_divider)
                .build());
        ptrFrame.setPtrHandler(new PtrHandler() {
            @Override
            public void onRefreshBegin(PtrFrameLayout frame) {
                getOrderList();
            }

            @Override
            public boolean checkCanDoRefresh(PtrFrameLayout frame, View content, View header) {
                return PtrDefaultHandler.checkContentCanBePulledDown(frame, recyclerView, header);
            }
        });
    }

    private void bind1(ViewHolder listHolder, final Voucher item, final int position) {
        ImageView img = listHolder.getView(R.id.img);
        Glide.with(mContext).load(item.getShopLogo()).error(R.mipmap.ic_default).into(img);
        ((TextView) listHolder.getView(R.id.desc)).setText(item.getTitle());
        ((TextView) listHolder.getView(R.id.title)).setText(item.getShopName());
        ((TextView) listHolder.getView(R.id.time)).setText(String.format("有效期至%s", item.getEndDate()));
        //((TextView)listHolder.getView(R.id.btn_comment)).setVisibility(item.getIsComment()==0?View.VISIBLE:View.GONE);
        ((TextView) listHolder.getView(R.id.btn_comment)).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (item.getStatus() == 0) {
                    //使用接口
                    AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
                    builder.setTitle("温馨提示");
                    builder.setMessage("是否立即使用？");
                    builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                        }
                    });
                    builder.setPositiveButton("使用", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            useCoupon(item.getId(), position);
                            dialog.dismiss();
                        }
                    });
                    builder.show();
                } else if (item.getIsComment() == 0) {
                    intent = new Intent(mContext, MakeCouponCommentActivity.class);
                    intent.putExtra("couponId", item.getId());
                    intent.putExtra("shopName", item.getShopName());
                    startActivity(intent);
                }
            }
        });
        TextView btnComment = listHolder.getView(R.id.btn_comment);
        LinearLayout layout = listHolder.getView(R.id.ll_bg);
        ImageView imgFlag = listHolder.getView(R.id.img_flag);
        if (item.getStatus() == 1) {
            //已使用
            //btnComment.setVisibility(item.getIsComment() == 0 ? View.VISIBLE : View.GONE);
            btnComment.setText(item.getIsComment() == 0 ? "评价" : "已评价");
            layout.setBackgroundResource(item.getIsComment() == 0?R.mipmap.shop_coupon_bg:R.mipmap.shop_coupon_bg_gray);
            imgFlag.setVisibility(View.GONE);
        } else if (item.getStatus() == 2) {
            //已过期
            btnComment.setVisibility(View.VISIBLE);
            btnComment.setText("已过期");
            layout.setBackgroundResource(R.mipmap.shop_coupon_bg_gray);
            imgFlag.setVisibility(View.GONE);
        } else {
            btnComment.setText("使用");
            btnComment.setVisibility(View.VISIBLE);
            layout.setBackgroundResource(R.mipmap.shop_coupon_bg);
            imgFlag.setVisibility(View.GONE);
        }
    }


    private void bind(ViewHolder listHolder, Voucher item, int position) {

        if (item.getStatus() == 1) {
            //已使用
            listHolder.getView(R.id.layout1).setBackgroundResource(R.mipmap.voucher_left_used);
            listHolder.getView(R.id.img_flag).setVisibility(View.VISIBLE);
            ((ImageView) listHolder.getView(R.id.img_flag)).setImageResource(R.mipmap.voucher_used);
        } else if (item.getStatus() == 2) {
            //已过期
            listHolder.getView(R.id.layout1).setBackgroundResource(R.mipmap.voucher_left_expired);
            listHolder.getView(R.id.img_flag).setVisibility(View.VISIBLE);
            ((ImageView) listHolder.getView(R.id.img_flag)).setImageResource(R.mipmap.voucher_expired);
        } else {
            listHolder.getView(R.id.layout1).setBackgroundResource(R.mipmap.voucher_left_unused);
            ((ImageView) listHolder.getView(R.id.img_flag)).setVisibility(View.GONE);
        }
        ((TextView) listHolder.getView(R.id.voucher_desc)).setText(item.getTitle());
        ((TextView) listHolder.getView(R.id.voucher_money)).setText(String.format("%s元", item.getMoney().setScale(2, RoundingMode.HALF_UP)));
        ((TextView) listHolder.getView(R.id.voucher_from)).setText("满"+item.getConditonMoney().setScale(0,RoundingMode.HALF_UP)+"使用");
        ((TextView) listHolder.getView(R.id.voucher_time)).setText(String.format("有效期至%s", item.getEndDate()));

    }

    private void getOrderList() {
        showLoadingDialog(0);
        Call<ResultDO<List<Voucher>>> call = ApiClient.getApiAdapter().getVoucherList(memberId,
                type, null, null);
        call.enqueue(new Callback<ResultDO<List<Voucher>>>() {
            @Override
            public void onResponse(Call<ResultDO<List<Voucher>>> call, Response<ResultDO<List<Voucher>>> response) {
                if (isFinish) {
                    return;
                }
                dissMissDialog();
                ptrFrame.refreshComplete();
                ResultDO<List<Voucher>> resultDO = response.body();
                if (resultDO != null) {
                    if (resultDO.getCode() == 0) {
                        if (resultDO.getResult() == null) {
                            return;
                        }
                        dataSet.clear();
                        dataSet.addAll(resultDO.getResult());
                        if (dataSet.size() == 0) {
                            emptyLayout.setErrorType(EmptyLayout.NODATA);
                            emptyLayout.setNoDataContent("暂无数据");
                        } else {
                            emptyLayout.setErrorType(EmptyLayout.HIDE_LAYOUT);
                        }
                        adapter.notifyDataSetChanged();
                    } else {
                        emptyLayout.setErrorType(EmptyLayout.NETWORK_ERROR);
                    }
                } else {
                    emptyLayout.setErrorType(EmptyLayout.NETWORK_ERROR);
                }
            }

            @Override
            public void onFailure(Call<ResultDO<List<Voucher>>> call, Throwable t) {
                dissMissDialog();
                ptrFrame.refreshComplete();
                emptyLayout.setErrorType(EmptyLayout.NETWORK_ERROR);
            }
        });
    }

    private void useCoupon(int id, final int position) {
        showLoadingDialog(0);
        Call<ResultDO> call = ApiClient.getApiAdapter().useCoupon(id);
        call.enqueue(new Callback<ResultDO>() {
            @Override
            public void onResponse(Call<ResultDO> call, Response<ResultDO> response) {
                if (isFinish) {
                    return;
                }
                dissMissDialog();
                ResultDO resultDO = response.body();
                if (resultDO != null) {
                    if (resultDO.getCode() == 0) {
                        dataSet.get(position).setStatus(1);
                        adapter.notifyItemChanged(position);
                    }
                }
            }

            @Override
            public void onFailure(Call<ResultDO> call, Throwable t) {
                dissMissDialog();
            }
        });
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        Log.v(TAG, "onActivityCreated" + type);
    }


    @Override
    public void onResume() {
        Log.v(TAG, "onResume" + type);
        super.onResume();
        if (getUserVisibleHint()) {
            getOrderList();
        }
    }
}